package com.woyao;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.app.Application;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.ApplyResponse;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.ChanceSummary;
import com.woyao.core.model.DemandSummary;
import com.woyao.core.model.GetChildHowResponse;
import com.woyao.core.model.GetMyDemandResponse;
import com.woyao.core.model.GetNextChanceSumaryResponse;
import com.woyao.core.model.How;
import com.woyao.core.model.KeyValue;
import com.woyao.core.model.KeyValueList;
import com.woyao.core.model.Manager;
import com.woyao.core.model.ProfileResponse;
import com.woyao.core.model.User;
import com.woyao.core.service.AccountService;
import com.woyao.core.service.ChanceService;
import com.woyao.core.service.HowService;
import com.woyao.core.util.Common;
import com.woyao.core.util.DateUtil;
import com.woyao.core.util.ServiceFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import retrofit2.Call;

import static android.content.Context.LOCATION_SERVICE;
import static android.content.Context.MODE_PRIVATE;
import static com.woyao.WoyaoooApplication.userId;

public class ChancesFragmentSimple extends Fragment {
    private static final String FILE_PATH = Environment.getExternalStorageDirectory() + "/woyaoooupdate/";
    private static final String FILE_NAME = FILE_PATH + "woyaoooo" + DateUtil.format(new Date(), "yyMMddHHmmss") + ".apk";
    private String apk_path = "https://woyaohezuo.oss-cn-hangzhou.aliyuncs.com/woyaooo.apk";

    private ChancesFragmentSimple.OnChancesFragmentInteractionListener mListener;
    public View theview;
    Toolbar toolbar;

    private TextView matchDemand;
    List<String> mPermissionList = new ArrayList<>();
    ArrayList<String> howList = new ArrayList<>();
    private TextView statusTxt;
    android.support.v7.widget.CardView  applyBtn;
    android.support.v7.widget.CardView ignoreBtn;

    SwipeableCardView main_chance;
    public UserViewModel uvm;
    FrameLayout emptyAll;
    LinearLayout chanceAll;


    Button matchBtn;
    TextView summaryText;
    TextView ignoreText;
    TextView applyText;
    TextView socialText;
    ImageView matchness;
    TextView valueTxt;

    ChanceSummary chance = null;

    Boolean loading = false;

    ProgressDialog progressDialog;

    private Integer COMPLETE_ACCOUNT_CODE = 10;
    private Integer COMPLETE_LOCATION_CODE = 30;
    private Integer COMPLETE_CATEGORY_CODE = 55;   //
    private Integer COMPLETE_VEFIFY_CODE = 60;   //

    private Integer ADD_DEMAND_CODE = 2000;
    private Integer MODIFY_DEMAND_CODE = 3000;
    private Integer MODIFY_HOW_CODE = 3500;
    private Integer MYREGISTER_CODE = 4000;
    private Integer COMPLETE_PREFER_CODE = 6000;

    private Integer MY_LOGIN_CODE = 4500;
    private Integer MY_ADDMEMBER_CODE = 5000;

    private static final int ASKCONTACTS_CODE = 2;
    private static final int PERMISSION_REQUEST_STORAGE = 1;
    private static final int ASKLOCATION_CODE = 3;
    private Integer INSTALL_CODE = 333;
    private Integer ADD_UPDATE_CODE  =7000;
    private Integer ADD_MEMBER_CODE  =8000;
    private Integer CATEGORY_CODE = 1200;


    private String today;


    public ChancesFragmentSimple() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ChancesFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ChancesFragmentSimple newInstance(String param1, String param2) {
        ChancesFragmentSimple fragment = new ChancesFragmentSimple();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        uvm = ViewModelProviders.of(getActivity()).get(UserViewModel.class);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        theview = inflater.inflate(R.layout.fragment_chance_simple, container, false);

        toolbar = (Toolbar) theview.findViewById(R.id.toolBar);
////        toolbar.setLogo(R.drawable.ic_launcher);
        toolbar.setTitle("我要合作网");
        toolbar.inflateMenu(R.menu.chance);

        Menu menu = toolbar.getMenu();
        if (menu != null) {
            try {
                //如果不为空,就反射拿到menu的setOptionalIconsVisible方法
                Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                //暴力访问该方法
                method.setAccessible(true);
                //调用该方法显示icon
                method.invoke(menu, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                if (item.getItemId() == R.id.nav_search) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), SearchActivity.class);
                    startActivity(intent);
                }


                if (item.getItemId() == R.id.nav_publish_demand) {

                    if (!WoyaoooApplication.hasLogin) {
                        Intent intent = new Intent();
                        intent.setClass(getContext(), RegisterActivity.class);
                        startActivityForResult(intent, MYREGISTER_CODE);
                        return false;
                    }


                    if ( uvm.getUser().getDisplayname().equals("") ){
                        Dialog alertDialog = new AlertDialog.Builder(getContext()).
                                setTitle("信息").
                                setMessage("请填写个人资料").
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        CompleteAccount();
                                    }
                                }).
                                create();
                        alertDialog.show();
                        return false;
                    }

//                    if ( uvm.getUser().getDemand_id() == 0 ){

//                        Dialog alertDialog = new AlertDialog.Builder(getContext()).
//                                setTitle("信息").
//                                setMessage("请说明业务情况").
//                                setIcon(R.drawable.ic_launcher).
//                                setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
                                        AddDemand();
//                                    }
//                                }).
//                                create();
//                        alertDialog.show();
//                        return false;
//                    }

//                        Intent intent = new Intent();
//                        intent.putExtra("id", 0);
//                        intent.putExtra("category", "other");
//                        intent.setClass(getContext(), MoveActivity.class);
//                        startActivityForResult(intent, ADD_UPDATE_CODE);
                }


                if (item.getItemId() == R.id.nav_add_member) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), ConfirmOrgActivity.class);
                    startActivityForResult(intent, MY_ADDMEMBER_CODE);
                }

//                if (item.getItemId() == R.id.nav_add_user) {
//                    Intent intent = new Intent();
//                    intent.setClass(getContext(), InviteActivity.class);
//                    startActivity(intent);
//                }

                if (item.getItemId() == R.id.nav_add_partner) {
                    if (!WoyaoooApplication.hasLogin) {
                        Intent intent = new Intent();
                        intent.setClass(getContext(), RegisterActivity.class);
                        startActivityForResult(intent, MYREGISTER_CODE);
                        return false;
                    }
//                    mListener.onTabChance(R.id.cooperate);
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RelationActivity.class);
                    intent.putExtra("is_new", true);
                    startActivity(intent);
                }
                return false;
            }
        });

        matchDemand = (TextView) theview.findViewById(R.id.id_demand_title);

        matchness = (ImageView)  theview.findViewById(R.id.id_matchness);

        valueTxt = (TextView)  theview.findViewById(R.id.id_value);

        LinearLayout switchDemand = (LinearLayout) theview.findViewById(R.id.id_demand_switch);

        switchDemand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchDemands();
            }
        });

        ImageView editDemand = (ImageView) theview.findViewById(R.id.id_demand_edit);

        editDemand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                modifyDemand();
            }
        });

        ImageView modifyPreferView = (ImageView) theview.findViewById(R.id.id_modify_prefer);

        modifyPreferView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                modifyPrefer();
            }
        });

        summaryText = (TextView) theview.findViewById(R.id.id_chances_summary);

        socialText = (TextView) theview.findViewById(R.id.id_social);
        statusTxt = (TextView) theview.findViewById(R.id.id_status_text);


        emptyAll = (FrameLayout) theview.findViewById(R.id.id_chance_empty);

        chanceAll = (LinearLayout) theview.findViewById(R.id.chanceAll);


        main_chance = (SwipeableCardView) theview.findViewById(R.id.chance_main);


        main_chance.setOnSwipeListener(new SwipeableCardView.OnSwipeListener() {
            @Override
            public void onSwipeLeft() {
                ignore();
//                Toast.makeText(getContext(), "向左滑动", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSwipeRight() {
                applyIt("");
//                ignore();
//                Toast.makeText(getContext(), "向右滑动", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSwipeUp() {
                applyIt("");
//                ignore();
//                Toast.makeText(getContext(), "向上滑动", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSwipeDown() {
                ignore();
//                Toast.makeText(getContext(), "向下滑动", Toast.LENGTH_SHORT).show();
            }
        });

        Button publishBtn = (Button) theview.findViewById(R.id.chance_publish);

        publishBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AddDemand();
            }
        });

        matchBtn = (Button) theview.findViewById(R.id.chance_match);

        matchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
////                        calendar.add(Calendar.DATE, 1);
//                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                chance.setDisplaydate(formatter.format(calendar.getTime()) );

                Calendar calendar = Calendar.getInstance();
                calendar.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//                        calendar.add(Calendar.DATE, 1);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

                getChance(0);
            }
        });

        applyBtn = (android.support.v7.widget.CardView) theview.findViewById(R.id.id_apply);

        applyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!WoyaoooApplication.hasLogin) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent, MYREGISTER_CODE);
                    return;
                }
                applyIt("");
//                if (chance.getObject_status().equals("apply")) {
//                    applyIt("");
//                } else {
//                    confirmApply();
//                }

            }
        });

        ignoreBtn = (android.support.v7.widget.CardView) theview.findViewById(R.id.id_ignore);

        ignoreBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (!WoyaoooApplication.hasLogin) {
//                    Intent intent = new Intent();
//                    intent.setClass(getContext(), RegisterActivity.class);
//                    startActivityForResult(intent, MYREGISTER_CODE);
//                    return;
//                }

               ignore();

            }
        });

        ignoreText = (TextView) theview.findViewById(R.id.id_ignore_text);
        applyText = (TextView) theview.findViewById(R.id.id_apply_text);

        showEmpty(  );

        initData();

        return theview;
    }

    private  void ignore(){
        if (chance.getObject_status().equals("apply")){
            Dialog alertDialog = new AlertDialog.Builder(getContext()).
                    setTitle("信息").
                    setMessage("对方希望对接合作，放弃这个机会吗？").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            getChance(chance.getPid());
                        }
                    }).
                    setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).
                    create();
            alertDialog.show();
        }else {

            getChance(chance.getPid());
        }
    }

    private void initData() {

        loadHows();
        loadProfile();

        Uri uri = getActivity().getIntent().getData();
        if (uri != null) {
            try {


                String bid = uri.getQueryParameter("bid");
                String rid = uri.getQueryParameter("rid");

                if (bid != null) {

                    Intent intent = new Intent();
                    intent.putExtra("from", "main");
                    intent.putExtra("id",  Integer.parseInt(bid ) );
                    intent.setClass(getContext(), ChanceViewActivity.class);
                    startActivity(intent);

                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }




        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        today = formatter.format(calendar.getTime());

    }


    private void markIt(  ) {

        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return ;
        }
        if (chance.getMarked()) {
            Common.showSnack(getContext(), matchBtn, "取消关注...");
        }else{
            Common.showSnack(getContext(), matchBtn, "关注...");
        }

        chance.setMarked(!chance.getMarked());

        final ImageView markImageView  = (ImageView) theview.findViewById(R.id.id_mark_image);

        AsyncTask<Void, Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {
                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<BaseResponse> responseCall = svc.mark(userId,chance.getPid(),chance.getId() ,chance.getMarked().toString().toLowerCase());
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {

                        if ( response != null) {
                            if (response.isSuccess()) {
                                if  (chance.getMarked()){
                                    markImageView.setImageResource(R.drawable.love_accent1);
                                }else{
                                    markImageView.setImageResource(R.drawable.love_empty);
                                }
                            }else{
                                Toast.makeText(getContext(),response.getMessage(),Toast.LENGTH_SHORT).show();
                                if (response.getCondition().equals("personal")){
                                    CompleteAccount();
                                }
                            }

                        }else{


                            Toast.makeText(getContext(),"抱歉,处理失败，请重试。",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onCancelled() {

                    }
                };
        task.execute((Void) null);

    }

    public  void modifyDemand(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }

//        if (chance == null || chance.getDemand_id() == 0){
//            AddDemand();
//            return;
//        }

        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        if (chance.getDemand_id() > 0) {
            intent.putExtra("is_new", false);
        }else{
            intent.putExtra("is_new", true);
        }
        intent.putExtra("id", uvm.getUser().getDemand_id() );
        intent.setClass(getContext(), DemandNewActivity.class);
        startActivityForResult(intent, MODIFY_DEMAND_CODE);
    }

    public  void AddDemand(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }
//        if ( uvm.getUser().getDisplayname().equals("") ){
//            Dialog alertDialog = new AlertDialog.Builder(getContext()).
//                    setTitle("信息").
//                    setMessage("请填写个人资料").
//                    setIcon(R.drawable.ic_launcher).
//                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            CompleteAccount();
//                        }
//                    }).
//                    create();
//            alertDialog.show();
//            return ;
//        }

        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.putExtra("is_new", true);
        intent.setClass(getContext(), DemandNewActivity.class);
        startActivityForResult(intent, ADD_DEMAND_CODE);
    }

    public  void modifyPrefer() {
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.setClass(getContext(), PreferActivity.class);
        startActivityForResult(intent ,COMPLETE_PREFER_CODE);
    }

    public  void CompleteLocation() {
        Intent intent = new Intent();
        intent.putExtra("from", "chance");
        intent.setClass(getContext(), ConfirmLocation.class);
        startActivityForResult(intent, COMPLETE_LOCATION_CODE);
    }

    public  void CompleteAccount(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.setClass(getContext(), AccountActivity.class);
        startActivityForResult(intent, COMPLETE_ACCOUNT_CODE);
    }
    public void renderVerify(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }
        Intent intent = new Intent();
        intent.setClass(getContext(), VerifyActivity.class);
        startActivityForResult(intent, COMPLETE_VEFIFY_CODE);
    }

    private void renderMoney( ){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("money", 100.0);
        intent.setClass(getContext(), MoneyActivity.class);
        startActivity(intent);
    }


    private void loadProfile() {

        final String version = Common.getCurrentVersion(getContext());

        AsyncTask<Void, Void, ProfileResponse> loadTask =
                new AsyncTask<Void, Void, ProfileResponse>() {
                    @Override
                    protected ProfileResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<ProfileResponse> responseCall = svc.getProfile(userId, "android",version);
                        try {
                            ProfileResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final ProfileResponse response) {
                        if (response != null && response.isSuccess()) {
                            Application application = getActivity().getApplication();
                            User user = response.getContent();

                            uvm.initUser( user);

                            SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);

                            SharedPreferences.Editor editor = shared.edit();
                            editor.putInt("demand_id", user.getDemand_id());
                            editor.putString("key", user.getKey());
                            editor.putString("displayname", user.getDisplayname());
                            editor.putString("snailview", user.getSnailview());
                            editor.putString("location", user.getLocation());
                            editor.putString("title", user.getTitle());
                            editor.putString("business", user.getBusiness());
                            editor.putString("business_name", user.getBusiness_name());
                            editor.putInt("member_id", user.getMember_id());
                            editor.putString("mobile", user.getMobile());
                            editor.commit();


                            WoyaoooApplication.key = user.getKey();
                            WoyaoooApplication.snailview = user.getSnailview();
                            WoyaoooApplication.displayname = user.getDisplayname();
                            WoyaoooApplication.location = user.getLocation();
                            WoyaoooApplication.title = user.getTitle();
                            WoyaoooApplication.member_id = user.getMember_id();
                            WoyaoooApplication.demand_id = user.getDemand_id();


                            mListener.onMessage(user.getChance_num(), "chance" );
                            mListener.onMessage(user.getMessage_num(), "talk" );
                            mListener.onMessage(user.getCooperate_num(), "cooperate" );
                            mListener.onMessage(user.getInterest_num(), "interest" );

                            summaryText.setText( user.getSummary());

                            matchDemand.setText( user.getDemand_title());
//                            if (user.getDemand_id()>0) {
                                getChance(0);
//                            }
                        }
                    }
                };
        loadTask.execute((Void) null);
    }


    public void getChance( final Integer pid) {

        if (chance != null && chance.getUnread() > 0) {
            mListener.onMessage(chance.getUnread() - 1,"chance");
        }
// 划出动画


        ConnectivityManager connMgr = (ConnectivityManager)
                getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null || !networkInfo.isConnected()) {
            Dialog alertDialog = new AlertDialog.Builder(getContext()).
                    setTitle("错误").
                    setMessage("没有网络，请检查设置！").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            getChance(pid);
                        }
                    }).
                    create();
            alertDialog.show();

            return;
        }

        if (loading) {
//            Toast.makeText(this, "正在加载...", Toast.LENGTH_SHORT).show();
            return;
        }

        progressDialog = new ProgressDialog(getContext());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("获取机会···");
        progressDialog.show();
        loading = true;
        String login = "false";
        if (WoyaoooApplication.hasLogin) {
            login = "true";
        }
        final String loginstr = login;

        AsyncTask<Void, Void, GetNextChanceSumaryResponse> task = new AsyncTask<Void, Void, GetNextChanceSumaryResponse>() {
            @Override
            protected GetNextChanceSumaryResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<GetNextChanceSumaryResponse> responseCall = svc.next(userId,loginstr,pid);
                GetNextChanceSumaryResponse ret = null;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final GetNextChanceSumaryResponse resp) {
                progressDialog.dismiss();
                loading = false;
                if (resp != null) {

                    if (resp.isSuccess()) {
                        chance = resp.getContent();
                        if (!resp.getMessage().equals("")) {
                            Common.alert(getContext(), resp.getMessage());
                        }

                        if (chance != null) {
                            renderChance();
                            return;
                        } else {
                            Common.alert(getContext(), "获取机会失败，请重试！");
                        }
                    }else{

                        if (resp.getType().equals("must") || resp.getType().equals("info") ){

                            if ( resp.getMessage().equals("")){
                                handleCondition( resp);
                                return;
                            }

                            Dialog alertDialog = new AlertDialog.Builder(getContext()).
                                    setTitle("信息").
                                    setMessage(resp.getMessage()).
                                    setIcon(R.drawable.ic_launcher).
                                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            handleCondition( resp);
                                        }
                                    }).
                                    create();
                            alertDialog.show();
                            return;
                        }

                        if (resp.getType().equals("optional")){
                            Dialog alertDialog = new AlertDialog.Builder(getContext()).
                                    setTitle("信息").
                                    setMessage(resp.getMessage()).
                                    setIcon(R.drawable.ic_launcher).
                                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            handleCondition( resp);
                                        }
                                    }).
                                    setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    }).
                                    create();
                            alertDialog.show();
                            return;
                        }


                    }
                } else {

                    Common.showSnack(getContext(), matchBtn, "请检查网络后重试！");

                }


            }

            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
                loading = false;
                Common.showSnack(getContext(), matchBtn, "没有成功获取新机会！");

            }
        };
        task.execute((Void) null);

    }

    private void renderChance( ){
        ObjectAnimator slideOutAnimator = ObjectAnimator.ofFloat(main_chance, "translationX", 0f, main_chance.getWidth()*2);
        slideOutAnimator.setDuration(500);
        slideOutAnimator.start();
// 划入动画
        if (chance == null){
            showEmpty();
            return;
        }
        chanceAll.setVisibility(View.VISIBLE);
        emptyAll.setVisibility(View.GONE);

        applyBtn.setEnabled( true );

        if (chance.getStatus_text().equals("") ){
            statusTxt.setVisibility(View.INVISIBLE);
        }else {
            statusTxt.setVisibility(View.VISIBLE);
        }
        statusTxt.setText(chance.getStatus_text());

        socialText.setText( chance.getSocial());
        if ( !chance.getDemand_title().equals("")) {
            matchDemand.setText(chance.getDemand_title());
        }

        if ( !chance.getIgnore_text().equals("")) {
            ignoreText.setText(chance.getIgnore_text());
            ignoreText.setVisibility(View.VISIBLE);
        }else {
            ignoreText.setVisibility(View.GONE);
        }

        if ( !chance.getApply_text().equals("")) {
            applyText.setText(chance.getApply_text());
            applyText.setVisibility(View.VISIBLE);
        }else {
            applyText.setVisibility(View.GONE);
        }

        if (!chance.getMessage().equals("")) {
            new AlertDialog.Builder(getContext())
                    .setTitle("信息")
                    .setMessage(chance.getMessage())
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    }).create().show();
        }

        if (chance.getDisplaydate() == null) {
            chance.setDisplaydate(new Date());
        }

        if ( chance.getMatchness() == null || chance.getMatchness().equals("")){
            matchness.setVisibility(View.GONE);
        }else{
            matchness.setVisibility(View.VISIBLE);

            Picasso.with(getContext())
                    .load(chance.getMatchness())
                    .into(matchness );

        }

        if ( chance.getValue() == null || chance.getValue().equals("")){
            valueTxt.setVisibility(View.GONE);
        }else{
            valueTxt.setVisibility(View.VISIBLE);
            valueTxt.setText( chance.getValue());
        }


        TextView theTitle = (TextView) theview.findViewById(R.id.id_fulltitle);
        final VideoView video = (VideoView) theview.findViewById(R.id.videoView);
        final ImageView image = (ImageView) theview.findViewById(R.id.pic);
        TextView desc = (TextView) theview.findViewById(R.id.chance_desc);
        de.hdodenhof.circleimageview.CircleImageView owner_avartar  = (de.hdodenhof.circleimageview.CircleImageView) theview.findViewById(R.id.owner_avatar);
        TextView owner_displayname = (TextView) theview.findViewById(R.id.owner_displayname);
        TextView owner_company_job = (TextView) theview.findViewById(R.id.owner_company_job);
        TextView owner_location = (TextView) theview.findViewById(R.id.owner_location);
        LinearLayout detailmore = (LinearLayout) theview.findViewById(R.id.id_chance_detailmore);
        LinearLayout talkit = (LinearLayout) theview.findViewById(R.id.id_talk);
        ImageView markImageView = (ImageView) theview.findViewById(R.id.id_mark_image);
        LinearLayout markAction = (LinearLayout) theview.findViewById(R.id.id_mark);
        LinearLayout referAction = (LinearLayout) theview.findViewById(R.id.id_refer);


        theTitle.setText(chance.getTitle() );
        desc.setText(chance.getDescription());
        final Manager manager = chance.getManager();
        owner_displayname.setText( manager.getDisplayname() );
        owner_company_job.setText(manager.getRole());
        owner_location.setText(manager.getLocation());

        if (chance.getMarked()){
            markImageView.setImageResource(R.drawable.love_accent1);
        }else{
            markImageView.setImageResource(R.drawable.love_empty);
        }

        Picasso.with(getContext())
                .load(manager.getSnailview())
                .into(owner_avartar );



        markAction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                markIt();
            }
        });



        referAction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                referIt();
            }
        });


        owner_avartar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("id", manager.getId() );
                intent.setClass(getContext(), PersonViewActivity.class);
                startActivity(intent);
            }
        });

        talkit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("from", "main");
                intent.putExtra("id", chance.getPid());
                intent.putExtra("bid", chance.getId());
                intent.putExtra("type", "match");
                intent.setClass(getContext(), TalkActivity.class);
                startActivity(intent);

            }
        });

        detailmore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("from", "main");
                intent.putExtra("pid", chance.getPid());
                intent.putExtra("id", chance.getId());
                intent.setClass(getContext(), ChanceViewActivity.class);
                startActivity(intent);
            }
        });

        if (!chance.getVideo().equals("")) {
            video.setVisibility(View.VISIBLE);
            image.setVisibility(View.INVISIBLE);
            video.setVideoPath(chance.getVideo());
            video.start();
            chance.setImage(  Common.getVideoSnapFile(chance.getVideo(), getContext()) );

            video.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (video.isPlaying()) {
                        video.pause();
                    }else{
                        video.start();
                    }
                }
            });

        } else {
            video.setVisibility(View.INVISIBLE);
            image.setVisibility(View.VISIBLE);
        }

        Picasso.with(getContext())
                .load(chance.getImage())
                .into(image );

        if (!chance.getCaption().equals("")) {
            toolbar.setTitle(chance.getCaption());
        }else{
            toolbar.setTitle("我要合作网");
        }

        mListener.onMessage(chance.getUnread(), "chance" );
        ObjectAnimator slideInAnimator = ObjectAnimator.ofFloat(main_chance, "translationX", -main_chance.getWidth(), 0f);
        slideInAnimator.setDuration(500); // 设置动画时长
        slideInAnimator.start(); // 启动动画

    }
    private void referIt(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return ;
        }

        Intent intent = new Intent();
        intent.setClass(getContext(), ReferActivity.class);
        intent.putExtra( "title", chance.getTitle());

        Manager theManager = chance.getManager();

        intent.putExtra("description", chance.getDescription() +  "\n " +theManager.getRole() + "\n " + theManager.getLocation() + "\n " +  theManager.getDisplayname() );

        intent.putExtra( "id", chance.getId() );
        ImageView tempShareImageView = (ImageView) theview.findViewById(R.id.id_temp_forshare);
        tempShareImageView.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(tempShareImageView.getDrawingCache());
        tempShareImageView.setDrawingCacheEnabled(false);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 90;
        while (baos.toByteArray().length / 1024 > 32) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        intent.putExtra("photo_bmp", baos.toByteArray());

        startActivity( intent );
    }
    private void handleCondition(GetNextChanceSumaryResponse resp){



        Intent intent = new Intent();
        switch ( resp.getCondition()) {
            case "register":
                intent.setClass(getContext(), RegisterActivity.class);
                startActivityForResult(intent,MYREGISTER_CODE);
                return;
            case "login":
                intent.setClass(getContext(), LoginActivity.class);
                startActivityForResult(intent,MY_LOGIN_CODE);
                return;
            case "position":
                TryGetCurrentLocation();
                return;
            case "upgrade":
                apk_path = resp.getContent().getDescription().trim();
                if ( checkStoragePermission() ) {
                    showDownloadDialog();
                }
                getChance(0);
                return;
            case "verify" :
                renderVerify();
                break;

            case "charge" :
                renderMoney();
                showEmpty();
                break;
            case "personal":
                CompleteAccount();
                break;
            case "demand":
                AddDemand();
                break;
            case "member":
                AddMember();
                break;
            case "location":
                CompleteLocation();
                break;
            case "category":
                modifyCategory();
                break;
            case "modifydemand":
                modifyDemand();
                break;
            case "prefer":
                modifyPrefer();
                break;
            case "how":
                confirmHow();
                break;
            case "empty":
                showEmpty();
                break;
            default :
                Log.i("ChancesFragment","nothing");
        }


    }
    public  void confirmHow() {
        User user = uvm.getUser();
        Intent intent = new Intent();
        intent.putExtra("from", "filter");
        intent.putExtra("type", "");

        KeyValueList kvl = new KeyValueList();
        kvl.setContent( user.getHow_list() );
        intent.putExtra("how_list", kvl  );

        intent.setClass(getContext(), FilterHow.class);
        startActivityForResult(intent, MODIFY_HOW_CODE);
    }



    private void AddMember(){
        Intent intent = new Intent();
        intent.putExtra("from","mymember");
        intent.putExtra("id",0);

        intent.setClass(getContext(), ConfirmOrgActivity.class);

        startActivityForResult(intent, ADD_MEMBER_CODE);
    }

    private void modifyCategory(){
        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        KeyValueList kvl = new KeyValueList();
        kvl.setContent( uvm.getUser().getCategory_list() );
        intent.putExtra("category_list", kvl  );
        intent.setClass(getContext(), FilterCategory.class);
        startActivityForResult(intent ,COMPLETE_CATEGORY_CODE);
    }
    public  void TryGetCurrentLocation() {

        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions( new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ASKLOCATION_CODE);
        } else {
            getCurrentLocation();
        }
    }

    public  void getCurrentLocation() {
        try {
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }

            LocationManager mLocationManager = (LocationManager) getActivity().getApplication().getSystemService(LOCATION_SERVICE);
            List<String> all_providers = mLocationManager.getProviders(true);
            Location bestLocation = null;
            for (String provider : all_providers) {
                Location l = mLocationManager.getLastKnownLocation(provider);
                if (l == null) {
                    continue;
                }
                if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                    // Found best last known location: %s", l);
                    bestLocation = l;
                }
            }

            if (bestLocation != null) {
                String longitude = bestLocation.getLongitude() + "";
                String latitude = bestLocation.getLatitude() + "";
                changeProfile("lnglat", longitude +"#" +latitude);
                return;
            }
        }catch (Exception e) {
            Toast.makeText(getContext(),"精准匹配合作，请授权访问定位。",Toast.LENGTH_LONG);
        }
        CompleteLocation();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_STORAGE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED ) {
                    showDownloadDialog();
//                    new AlertDialog.Builder(getContext())
//                            .setTitle("下载新版本")
//                            .setMessage("")
//                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    dialog.dismiss();
//                                    showDownloadDialog();
//                                    return;
//                                }
//                            }).create().show();
                } else {
                    new AlertDialog.Builder(getContext())
                            .setTitle("授权访问存储设备")
                            .setMessage("请授权，才可以升级")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();

                }
                // getBatch
                break;
            case ASKLOCATION_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getCurrentLocation();

                } else {
                    CompleteLocation();
//                    Log.i("woyaooo", "onRequestPermissionsResult:  fail");
//                    Dialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).
//                            setTitle("信息").
//                            setMessage("为您整合附近的资源，请授权访问定位").
//                            setIcon(R.drawable.ic_launcher).
//                            setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//
//                                }
//                            }).
//                            create();
//                    alertDialog.show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                break;
            case ASKCONTACTS_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    getContacts();
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
                // other 'case' lines to check for other
                // permissions this app might request
            }
        }
    }


    private void loadUserBasic(){
        Application application = getActivity().getApplication();
        SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);

        try {
            WoyaoooApplication.hasLogin = shared.getBoolean("logged", false);
            WoyaoooApplication.userId = shared.getInt("userId", 0);
            WoyaoooApplication.displayname = shared.getString("displayname", "");;
            WoyaoooApplication.location = shared.getString("location", "");
            WoyaoooApplication.title = shared.getString("title", "");
            WoyaoooApplication.snailview = shared.getString("snailview", "");
            WoyaoooApplication.demand_id = shared.getInt("demand_id",0);
        }catch (Exception e){

        }

    }
    @Override
    public void onResume() {
        super.onResume();
        loadUserBasic();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String theday = formatter.format(calendar.getTime());
        if (!theday.equals(today)  ) {
            uvm.getUser().businessChanged = true;
            uvm.getUser().cooperateChanged = true;
            today = theday;
            loadProfile();
        }



    }



    private void showEmpty(  ) {

        chanceAll.setVisibility(View.GONE);
        emptyAll.setVisibility(View.VISIBLE);

        toolbar.setTitle("我要合作网");
        if (uvm != null) {
            mListener.onMessage(0,"chance");
        }
    }
    int yourChoice = 0 ;
    private void confirmApply(){

        final String[] items =  (String[])howList.toArray(new String[0]);

//        AlertDialog.Builder listDialogBuilder = new AlertDialog.Builder(getContext());
//        listDialogBuilder.setTitle("请选择合作方式");
//
//        ListView listView = new ListView(getContext());
//        ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, items);
//        listView.setAdapter(adapter);
//
//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                String selectedItem = items[position];
//                applyIt(items[position]);
//                Toast.makeText(getContext(), "你选择了: " + selectedItem, Toast.LENGTH_SHORT).show();
//                // 关闭弹窗
//                ((AlertDialog) parent.getParent()).cancel();
//            }
//        });
//
//        listDialogBuilder.setView(listView);
//        listDialogBuilder.setNegativeButton("关闭", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.cancel();
//            }
//        });
//
//        AlertDialog listDialog = listDialogBuilder.create();
//        listDialog.show();


        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(getContext());
        singleChoiceDialog.setTitle("请选择希望合作的方式");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, yourChoice,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        yourChoice = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确 定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        applyIt(items[yourChoice]);
                    }
                });
        singleChoiceDialog.setNegativeButton("取 消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        singleChoiceDialog.show();
    }


    private void loadHows(){
        AsyncTask<Void,Void, GetChildHowResponse> task =
                new AsyncTask<Void, Void, GetChildHowResponse>() {
                    @Override
                    protected GetChildHowResponse doInBackground(Void... params) {
                        HowService svc = ServiceFactory.get(HowService.class);
                        Call<GetChildHowResponse> responseCall = svc.getChildHow("all",WoyaoooApplication.userId,"");
                        try {
                            GetChildHowResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    @Override
                    protected void onPostExecute(final GetChildHowResponse response) {

                        ArrayList<How> hows = response.getHowList();
                        howList.clear();
                        for( How hw : hows){
                            howList.add(hw.getName());
                        }
                    }
                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute();
    }
    private int demandChoice =0 ;
    private void switchDemands(){

        AsyncTask<Void, Void, GetMyDemandResponse> task =new AsyncTask<Void, Void, GetMyDemandResponse>() {
            @Override
            protected GetMyDemandResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyDemandResponse> responseCall = svc.getMyDemand(WoyaoooApplication.userId, "false");
                try {
                    GetMyDemandResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyDemandResponse response) {

                final List<DemandSummary> demands = response.getContent();
                ArrayList<String> demandList = new ArrayList<String>();
                final ArrayList<Integer> demandIdList = new ArrayList<Integer>();
                Integer curIndex = 0;
                for ( DemandSummary ds : demands){
                    demandList.add( ds.getTitle());
                    demandIdList.add(ds.getId());
                    if (ds.getId() == WoyaoooApplication.demand_id){
                        demandChoice = curIndex;
                    }
                    curIndex += 1;
                }

                demandList.add( "新建业务");
                demandIdList.add(0);
                final String[] items = demandList.toArray(new String[0]);

                AlertDialog.Builder singleChoiceDialog =
                        new AlertDialog.Builder(getContext());
                singleChoiceDialog.setTitle("选择匹配的业务");
                // 第二个参数是默认选项，此处设置为0
                singleChoiceDialog.setSingleChoiceItems(items, demandChoice,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                demandChoice = which;
                            }
                        });
                singleChoiceDialog.setPositiveButton("确 定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (demandIdList.get(demandChoice) == 0 )
                                {
                                    AddDemand();
                                }else {
                                    matchDemand.setText(items[demandChoice]);
                                    changeProfile("demand_id", demandIdList.get(demandChoice) + "");
                                }
                            }
                        });
                singleChoiceDialog.setNegativeButton("取 消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                singleChoiceDialog.show();

            }
            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void)null);

    }



    private void applyIt( final String how) {
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }

        applyBtn.setEnabled( false);

        AsyncTask<Void, Void, ApplyResponse> task =
                new AsyncTask<Void, Void, ApplyResponse>() {
                    boolean bizComplete = false;

                    @Override
                    protected ApplyResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<ApplyResponse> responseCall = svc.apply(userId,how, chance.getId(),0  ,chance.getPid(),0);
                        try {
                            ApplyResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final ApplyResponse response) {
                        progressDialog.dismiss();
                        applyBtn.setEnabled( true );
                        if ( response != null) {
                            if (response.isSuccess()) {
                                String msg = response.getMessage();

                                if (!msg.equals("")){
                                   Toast.makeText(getContext(),msg,Toast.LENGTH_LONG).show();
                                    
                                }
                                    
                                getChance(0);

                                uvm.getUser().cooperateChanged = true;
                                

                            }else{

                                if (response.getMessage().equals("")) {
                                    switch (response.getCondition()) {
                                        case "verify":
                                            renderVerify();
                                            break;
                                        case "charge":
                                            renderMoney();
                                            break;
                                        case "personal":
                                            CompleteAccount();
                                            break;
                                        case "demand":
                                            AddDemand();
                                            break;

                                        default:
                                    }
                                }else{
                                    Dialog alertDialog = new AlertDialog.Builder(getContext()).
                                            setTitle("信息").
                                            setMessage(response.getMessage()).
                                            setIcon(R.drawable.ic_launcher).
                                            setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    switch (response.getCondition()) {
                                                        case "verify":
                                                            renderVerify();
                                                            break;
                                                        case "charge":
                                                            renderMoney();
                                                            break;
                                                        case "personal":
                                                            CompleteAccount();
                                                            break;
                                                        case "demand":
                                                            AddDemand();
                                                            break;

                                                        default:
                                                    }
                                                }
                                            }).
                                            setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {

                                                }
                                            }).
                                            create();
                                    alertDialog.show();
                                }
                            }

                        }else{
                            Toast.makeText(getContext(),"抱歉,处理失败，请重试。",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                        applyBtn.setEnabled( true );
                    }
                };
        task.execute((Void) null);

    }


    private  void changeProfile( final String att, final String content){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setProfileAttr(WoyaoooApplication.userId,att,content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {
                    getChance(0);
//                    Toast.makeText(getContext(), "需求已经修改", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getContext(), "发生异常，请重试", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            protected void onCancelled() {
                Toast.makeText(getContext(), "发生异常，请重试", Toast.LENGTH_LONG).show();
            }
        };
        task.execute((Void) null);

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onChancesFragmentInteraction(uri);
        }
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof ChancesFragmentSimple.OnChancesFragmentInteractionListener) {
            mListener = (ChancesFragmentSimple.OnChancesFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnChancesFragmentInteractionListener {
        // TODO: Update argument type and name
        void onChancesFragmentInteraction(Uri uri);
        void onMessage(Integer messageNum, String info);
    }


    private boolean checkStoragePermission() {
        String[] permissions = new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE};
        boolean authorized = true ;
        mPermissionList.clear();

        //判断哪些权限未授予
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(getContext(), permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        /**
         * 判断是否为空
         */
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了

        } else {//请求权限方法
            requestPermissions( permissions, PERMISSION_REQUEST_STORAGE);
            authorized = false ;
        }
        return authorized;
    }

    /**
     * 显示下载进度对话框
     */
    public void showDownloadDialog() {

        progressDialog = new ProgressDialog(getContext());
        progressDialog.setTitle("正在下载...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        new ChancesFragmentSimple.downloadAsyncTask().execute();
    }

    /**
     * 下载新版本应用
     */
    private class downloadAsyncTask extends AsyncTask<Void, Integer, Integer> {

        @Override
        protected void onPreExecute() {

            progressDialog.show();
        }

        @Override
        protected Integer doInBackground(Void... params) {



            URL url;
            HttpURLConnection connection = null;
            InputStream in = null;
            FileOutputStream out = null;
            try {
                url = new URL(apk_path);
                connection = (HttpURLConnection) url.openConnection();

                in = connection.getInputStream();
                long fileLength = connection.getContentLength();
                File file_path = new File(FILE_PATH);
                if (!file_path.exists()) {
                    file_path.mkdirs();
                }

                out = new FileOutputStream(new File(FILE_NAME));//为指定的文件路径创建文件输出流
                byte[] buffer = new byte[1024 * 1024];
                int len = 0;
                long readLength = 0;


                while ((len = in.read(buffer)) != -1) {

                    out.write(buffer, 0, len);//从buffer的第0位开始读取len长度的字节到输出流
                    readLength += len;

                    int curProgress = (int) (((float) readLength / fileLength) * 100);


                    publishProgress(curProgress);

                    if (readLength >= fileLength) {

                        break;
                    }
                }

                out.flush();
                return 1;

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (connection != null) {
                    connection.disconnect();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {

            progressDialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Integer integer) {

            progressDialog.dismiss();//关闭进度条
            //安装应用
            installApp();
        }
    }

    /**
     * 安装新版本应用
     */
    private void installApp() {
        File appFile = new File(FILE_NAME);
        if (!appFile.exists()) {
            return;
        }
        // 跳转到新版本应用安装页面
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(getContext(), "com.woyao.app.fileprovider", appFile);//在AndroidManifest中的android:authorities值
            Log.d("======", "apkUri=" + apkUri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(appFile), "application/vnd.android.package-archive");
        }
        startActivityForResult(intent, INSTALL_CODE);


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == INSTALL_CODE){

            Log.e("woyaooo", "installed");
            Common.alert(getContext(),"升级完成");
        }


        if  (requestCode == COMPLETE_ACCOUNT_CODE ){
            String displayName = data.getStringExtra("displayname");
            uvm.getUser().setDisplayname( displayName);
            loadProfile();

        }



        if  (requestCode == MODIFY_DEMAND_CODE  ){   //add or change demand
            Integer demand_id = data.getIntExtra("demand_id",0);
            if (demand_id == 0) return;

            uvm.getUser().setDemand_id(demand_id);

            loadProfile();

        }

        if  (requestCode == ADD_DEMAND_CODE  ){   //add or change demand
            Integer demand_id = data.getIntExtra("demand_id",0);
            if (demand_id == 0) return;

            uvm.getUser().setDemand_id(demand_id);

            loadProfile();

            Toast.makeText(getContext(),"已经添加",Toast.LENGTH_LONG);


        }
        
        if  (requestCode == COMPLETE_LOCATION_CODE && resultCode ==666 ){
            String locationNo = data.getStringExtra("no");
            String locationName = data.getStringExtra("name");
            uvm.getUser().setLocation(locationName);
            uvm.getUser().setProvince( Integer.parseInt( locationNo));
            changeProfile("location", locationNo);

        }

        if  (requestCode == COMPLETE_CATEGORY_CODE && resultCode ==666 ){
//            String categoryNo = data.getStringExtra("category");
//            String categoryName = data.getStringExtra("category_name");
//
//            uvm.getUser().setCategory(categoryNo);
//            uvm.getUser().setCategory_name( categoryName);
//            changeProfile("category", categoryNo);


            KeyValueList thelist = (KeyValueList) data.getExtras().get("result");
            String nos = Common.KeyValueToNos(thelist.getContent());
            String names = Common.KeyValueToNames(thelist.getContent());
            uvm.getUser().setCategory(nos);
            uvm.getUser().setCategory_name( names);

            changeProfile("category",nos );



        }


        if  (requestCode == COMPLETE_PREFER_CODE && resultCode == 666 ){
            loadProfile();
        }

        if  (requestCode == MYREGISTER_CODE && resultCode == 666 ){
            loadProfile();
            toolbar.setTitle("我要合作网");
        }

        if  (requestCode == MY_LOGIN_CODE && resultCode == 666 ){
            loadProfile();
            toolbar.setTitle("我要合作网");
        }

        if  (requestCode == MODIFY_HOW_CODE && resultCode ==666){
            KeyValueList thelist = (KeyValueList ) data.getExtras().get("result");
            ArrayList< KeyValue > howlist = thelist.getContent();
            changeProfile("how",Common.KeyValueToNames(howlist) );

        }



       
    }

}
